<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select>
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="err">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="res(index)">删除</button>
            <button @click="eds(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: [
        { id: 1, name: "库里", age: 3, gender: "男" },
        { id: 2, name: "欧文", age: 13, gender: "男" },
        { id: 3, name: "小杜", age: 23, gender: "男" },
        { id: 4, name: "麦迪", age: 33, gender: "男" },
      ],
      name: "",
      age: "",
      sex: "",
      flag: "",
      fn: "",
    };
  },
  methods: {
    err() {
      if (this.name.length === 0 || this.age.length === 0) {
        return;
      }
      if (!this.flag) {
        this.arr.push({ name: this.name, age: this.age, gender: this.sex });
      } else {
        this.arr.splice(this.fn, 1, {
          name: this.name,
          age: this.age,
          gender: this.sex,
        });
        this.flag = false;
      }
      (this.name = ""), (this.age = 0), (this.sex = "");
    },
    res(a) {
      this.arr.splice(a, 1);
    },
    eds(i) {
      this.name = this.arr[i].name;
      this.age = this.arr[i].age;
      this.sex = this.arr[i].gender;
      this.fn = this.arr.findIndex((item) => item.id === i + 1);
      this.flag = true;
    },
  },
};
</script>
